## Vehicle For Traffic simulation
## Contains: driving Algorythm and data output
from __future__ import division
from math import sqrt
#import psyco #uncomment if psyco is loaded on your machine
#psyco.full()
class vehicle():
    def __init__(self,position,speed,TrackLength,CarNumber,TrackCar='Off',Speedlimit=33.33,T_Step=.25,Aggression=.5,T=2,So=2,a=.3,b=3,beta=4,S1=0):
        self.position=position
        self.speed=speed
        self.accel=0
        self.T_Step=T_Step
        self.TrackCar=TrackCar
        self.Speedlimit=Speedlimit
        self.TotalTime=0
        self.aggression=Aggression   # gets sent a gaussian random with mu=.9 and sigma=.15
        self.TrackLength=TrackLength
        self.AccelerationConst=self.aggression*3+.5
        self.CarNumber=CarNumber
        self.T=T
        self.a=a
        self.b=b
        self.beta=beta
        self.So=So
        self.S1=S1
        self.FlowFlag=0
        
   
        
        
    def step(self,next_car_pos,next_car_speed):  # gets called for each object
        self.FlowFlag=0
        if ((next_car_pos-self.position)<0):
            next_car_pos=next_car_pos+self.TrackLength
             #Decelerate
            #self.BreakLight='On'
        s=self.So+self.T*self.speed+self.speed*(self.speed-next_car_speed)/(2*(self.a*self.b)**0.5)
        pt1=(self.speed/self.Speedlimit)**self.beta
       # print next_car_pos
       # print self.position
        if next_car_pos==self.position:
            pt2=0
        else:
            pt2=(s/(next_car_pos-self.position))**2.0
        accel=self.a*(1-(pt1)-pt2)
        self.accel=accel# for debug
        self.speed=self.speed+self.accel*self.T_Step
        velo=self.speed# debug
        if self.speed<0:
            self.speed=0.0
        self.position=self.position+self.speed*self.T_Step
        position=self.position
        self.TotalTime=self.TotalTime+self.T_Step
        Time=self.TotalTime
        if self.position> self.TrackLength:
            self.position=self.position-self.TrackLength
            self.FlowFlag=1
            
        if (self.TrackCar in('On','on')):
            print str(self.CarNumber)+','+str(Time)+','+str(position)+','+str(velo)#+','+str(accel)
            #data output stdout is changed to a file in sim engine
            
    def setSpeed(self,speed):
        self.speed=speed


        
